<template>
  <div class="image-box-flex">
    <view class="image-box" v-if="fileList.length>0" v-for="(item, index) in fileList" :key="index">
      <image v-if="fileType=='img'" :src="item.url" @tap="onPreviewImage(item,index)" mode="aspectFill"/>
      <!--    <video v-if="fileType=='video' && item.url" id="myVideo" :src="item.url" controls/>-->
      <view v-if="fileType=='video'" @tap="onPreviewVideo(item,index)" class="file">{{item.name}}</view>
      <view v-if="fileType=='file'" @tap="onPreviewDoc(item,index)" class="file">{{item.name}}</view>
    </view>
    <view v-else>--</view>
  </div>
</template>
<script setup>
import api from '@/api/upload/upload';
import {ref, getCurrentInstance, watchEffect} from 'vue';

const {proxy} = getCurrentInstance();
const props = defineProps({
  tableId: {      // 表id
    type: String,
    default: ''
  },
  tableName: {    // 表名称
    type: String,
    default: ''
  },
  type: {         // 表文件类型
    type: String,
    default: ''
  },
  fileType: {     // 文件类型
    type: String,
    default: 'img'
  },
});
let fileList = ref([]); // 文件列表
let fileUrl = ref(''); // 文件路径

// 初始化数据
let init = async (e) => {
  if(props.tableId) {
    let query = {};
    query.tableId = props.tableId;
    query.tableName = props.tableName;
    query.type = [props.type];
    let res = await proxy.http.asyncPost(api.findFileList, query);
    if (res.code === 0) {
      fileList.value = res.data;
    } else {
      uni.showToast({title: res.msg, icon: 'none'});
    }
  }
}

// 预览图片
let onPreviewImage = (item, index)=> {
  let lists = fileList.value;
  uni.previewImage({
    // 先filter找出为图片的item，再返回filter结果中的图片url
    urls: lists.map((item) => item.url || item.thumb),
    current: index,
  });
};

// 预览文档
let onPreviewDoc = (item, index) => {
  uni.downloadFile({
    url: item.url,
    success: function (res) {
      var filePath = res.tempFilePath;
      uni.openDocument({
        filePath: filePath,
        showMenu: true,
        success: function (res) {
          console.log('打开文档成功');
        }
      });
    }
  });
}

// 查看视频
let onPreviewVideo = (item, index) => {
  fileUrl.value = item.url;
  uni.navigateTo({
    url: '/pages/customer/canteen/viewVideo?url='+fileUrl.value
  });
}

watchEffect(()=>{
  init();
})

</script>
<style scoped lang="scss">
.image-box-flex {
  display: flex;
  flex-wrap: wrap;
  gap: 0 10rpx;
}
.image-box {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-start;
  &:nth-child(5) {
    margin-top: 20rpx;
  }
  image {
    flex-shrink: 0;
    width: 144rpx;
    height: 144rpx;
    border-radius: 8rpx;
    margin-right: 10rpx;
  }
  .file{
    width: 200px;
    color:#3775F6;
    word-break: break-all;
    text-align: right;
  }
}
</style>